﻿<?xml version="1.0" ?>
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="root" profile="ecmascript" name="ImageTag">
  <parallel id="root">
    <state id="ui" initial="UnauthenticatedUserState">

      <!--sub state Unauthenicated-->
      <state id="UnauthenticatedUserState">
        <onentry>
          <if cond="(_data.login === null) || (_data.login === undefined)">
            <script>
              $('#refhome').show();
              _data.imagedemo = new ImageWidget('demo');
              _data.service = new WebService("../../Service1.asmx");
              _data.login = new LoginWidget("mylogin","",function(){raise('login');});
              with(_data){
                imagedemo.setPosition(20,10);
                imagedemo.setDimension(110,80);
                imagedemo.setUri('images/TagimagePrimaPagina.png');
                imagedemo.render("body",true,'slow',true,'slow');
                //login.setDimension("center",20);
                login.setDimension(20,20);
                login.setPosition(65,37);
                login.setDrag(true);
                login.setBackgroundImg('images/login.png');
                login.appendText("please [[register]]",new LinkSt("linkId",function(){raise("register");},"link_class","register"));
              }
              _data.login.render();
            </script>
          <else/>
            <script>
              $('#refhome').show();
              _data.imagedemo.render();
              _data.login.render();
              _data.login.showMe();
            </script>
          </if>
        </onentry>
        <onexit>
          <script>
            _data.imagedemo.deleteMe();
            _data.login.deleteMe();
          </script>
        </onexit>
        <transition event="login" target="LoginConnection" />
        <transition event="register" target="RegistrationState" />
      </state>

      <!-- connessione al web service -->
      <state id="LoginConnection">
        <onentry>
          <script>
            _data.logdatin = new loginData(_data.login.User,MD5(_data.login.Pass));
            _data.logdatout = new logoutData();
            try{
              with(_data){
                service.Login(logdatin,logdatout,function(){raise('feedBackLogin');});
              }
            }
            catch(error){
              if(error instanceof ConnectException)
                alert('Connection error');
            }
          </script>
        </onentry>
        <transition event="feedBackLogin" target="feedBack" />
      </state>

      <!-- controllo callback comunicazione server -->
      <state id="feedBack">
        <onentry>
          <script>
            if(_data.logdatout.connectionSuccess == true){
              if(_data.logdatout.logged === 'true'){
                alert('You are already logged in: '+_data.logdatout.userid);
              }
              raise('positive');
            }else {
              alert('Forgot your Username?');
              raise('negative');
              }
          </script>
        </onentry>
        <transition event="negative" target="UnauthenticatedUserState" />
        <transition event="positive" target="istruzioni" >
          <script>
            _data.imagedemo.deleteMe();
            _data.login.deleteMe();
            delete _data.imagedemo;
            delete _data.login;
          </script>
        </transition>
      </state>

      <!--sub state Registration-->
      <state id="RegistrationState" initial="modulo">
        <!-- eseguita all'ingresso dello stato -->
        <onentry>
          <script>
            _data.myButtonBack = new ButtonWidget('Back',function() {
              raise( 'back' );
            });
            with(_data){
              myButtonBack.setPosition(5,6);
              myButtonBack.setInnerText('Back');
              myButtonBack.render();
            }
          </script>
        </onentry>
        
        <!--State for registration account-->
        <state id="modulo">
          <onentry>
            <script>
              prepareField();

              function validatePass(id){
                if($('#'+id).val().length &lt; 6)
                  return 'la password deve avere almeno 6 caratteri';
                else return 'Ok';
              }

              function checkPass(){
                var pas1 = document.getElementById('registration_pass_pass').value;
                var pas2 = document.getElementById('registration_repass_pass').value;
                if(pas1 === pas2){
                  return 'Ok';
                }
                else
                  return 'Password non corrispondente';
              }

              function validateEmail() {
                var email = document.getElementById('registration_email_input');
                var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
                if (!filter.test(email.value)) {
                  alert('Please provide a valid email address');
                    return 'email inserita non valida';
                }
                return 'Ok';
              }

              function checkEmail(){
                var em1 = document.getElementById('registration_email_input').value;
                var em2 = document.getElementById('registration_remail_input').value;
                if(em1 === em2){
                  return 'Ok';
                }
                else {
                  return 'Email non corrispondente';
                }
              }

              _data.asd = new RegisterWidget("registration",function(){raise('submit');});

              with(_data){
                asd.addField("nick", "Nickname", {type:"input", mandatory:true});
                asd.addField("pass", "Password", {type: "pass", mandatory:true, validator:validatePass });
                asd.addField("repass", "Re-Password", {type:"pass", mandatory:true, validator:checkPass });
                asd.addField("email", "E-mail", {type:"input", mandatory:true, validator:validateEmail });
                asd.addField("remail", "ReE-mail", {type:"input", mandatory:true, validator:checkEmail });
                asd.addField("data", "Data di nascita", {type:"date", end: "+3m+2w-1d", show:'13/02/1997', start: null});
   		          //asd.addField("lecca", "Interessi", {type:"drop", mandatory:false, options:{1:"cazzeggio", 2:"mignotte", 8:"\"fiacco\"", 3:"violenza gratuita", 4:"salvare le balene", 5:"bombardare le balene", 9:"\"finto\"", 6:"bestemmiare", 7:"porno amatoriale", 10:"\"regolata\"" }});
                //asd.addField("data", "Data di morte presunta", {type:"date", end: "14/12/2113"});
                asd.render("game_area");
              }
              _data.sos = new HelpWidget("nckhlp", {content:"Inserisci un nickname valido di almeno 6 caratteri", button:"help", attach:"registration_nick label"});
              _data.sos.render();
            </script>
          </onentry>
          <transition event="submit" target="Registration" />
        </state>

        <!--state with call the web method registrer-->
        <state id="Registration">
          <onentry>
            <script>
              try{
                _data.regdataout = new Object();
                var nick = document.getElementById('registration_nick_input');
                var pass = document.getElementById('registration_pass_pass');
                var email = document.getElementById('registration_email_input');
                var msg = new messageRegister(nick.value,nick.value,nick.value,email.value,MD5(pass.value));
                _data.service.Register(msg,_data.regdataout,function(){raise('info');});
              }
              catch(e){
                if(e instanceof ConnectException)
                  alert('Connection error '+e.toString());
              }
            </script>
          </onentry>          
          <transition event="info" target="Info" />
        </state>

        <!--state view the information again the account-->
        <state id="Info">
          <onentry>
            <script>
              _data.myRegistration = new TextWidget("info");
              with(_data){
                if(regdataout.risposta == 'true'){
                  asd.deleteMe();
                  delete _data.asd;
                  myRegistration.setDimension(100,30);
                  myRegistration.setPosition(5,3);
                  myRegistration.setFont(20);
                  myRegistration.setInnerText('Complimenti ti sei registrato. Ora puoi giocare.');
                  myRegistration.render("game_area");
                  setTimeout(function(){raise('log');},2000);
                }
                else{
                  //alert(regdataout.msg);
                  if(regdataout.msg === 'user')
                    _data.asd.verify({'registration_nick_input': 'Il nickname scelto non è disponibile. Cambialo!'});
                  else if (regdataout.msg === 'email')
                    _data.asd.verify({'registration_email_input': 'E-mail gia registrata. Cambiala!'});
                  
                }
              }
            </script>
          </onentry>
          <onexit>
            <script>
              _data.myRegistration.deleteMe();
              delete _data.myRegistration; 
            </script>
          </onexit>
          <transition event="submit" target="Registration" />
          <transition event="log" target="UnauthenticatedUserState" >
            <script>              
              _data.sos.deleteMe();
              delete _data.sos;
              _data.myButtonBack.deleteMe();
              delete _data.myButtonBack;
              $("#game_area").empty();
              $("#game_area").hide();
            </script>
          </transition>
        </state>

       <!--transizione per tornare alla pagina login -->
       <transition event="back" target="UnauthenticatedUserState">
          <script>
            _data.asd.deleteMe(); //removing div from html
            delete _data.asd; //removing objgect from javascript
            _data.sos.deleteMe();
            delete _data.sos;
            _data.myButtonBack.deleteMe();
            delete _data.myButtonBack;
            $("#game_area").empty();
            $("#game_area").hide();
          </script>
        </transition>
      </state>

      <!-- immagine -->
      <state id="istruzioni">
        <onentry>
          <script>
            $('#refhome').hide();
            _data.loading = new TextWidget('ling');
            _data.loading.setInnerText('Loading...');
            _data.loading.setFont(30,'bolt');
            _data.loading.setColor('#000000');
            _data.loading.setPosition(85,15);
            _data.istr = new ImageWidget('istr');
            _data.istr.setPosition(20,10);
            _data.istr.setDimension(110,80);
            _data.istr.setUri("images/TagImage.png");
            _data.istr.render();
            _data.loading.render();
            setTimeout(function(){raise('start');},9000);
          </script>
        </onentry>
        <onexit>
          <script>
            _data.loading.deleteMe();
            _data.istr.deleteMe();
            delete _data.loading;
            delete _data.istr;
          </script>
        </onexit>
        <transition event="start" target="ImageTag" />
      </state>
      
      <!-- stato inizial del gioco -->
      <state id="ImageTag" initial="nuovo_step1">
        <datamodel>
          <data id="gamename" expr="'TagImage'" />
        </datamodel>
        <onentry>
          <assign location="_data.dataout" expr="new messageAnswer()" />
          <script>
            try{
              with(_data){
                var bool = false;
                service.setAsync(bool);
                service.GetScore(gamename,dataout);
                bool = true;
                service.setAsync(bool);
              }
            }
            catch(e){
              if(e instanceof ConnectException)
                alert('Connection error '+e);
              if(e instanceof IllegalArgumentException)
                alert('Invalid argument '+e);
            }
            _data.myStatusWi = new StatusWidget("myStatus",
              _data.logdatin.nickname,
              function() {
                try{
                  _data.service.Logout();
                } catch(e) {
                  if(e instanceof ConnectException)
                    alert('Connection error '+ e);
                }
                raise('logout');
              },
              "images/user.png",
              _data.dataout.score
            );
              
            with(_data){
              myStatusWi.setDimension(20,20);
              myStatusWi.setPosition(130,10);
              myStatusWi.setDrag(true);
              myStatusWi.setBackgroundImg("images/login.png");
              myStatusWi.render();
            }
            prepareField();

            _data.myDescr = new TextWidget("descr");
            with(_data){
              myDescr.setDimension(100,30);
              myDescr.setPosition(5,3);
              myDescr.setFont(20);
              myDescr.render("game_area");
              myDescr.hideMe();
            }

            _data.myImage = new ImageWidget("immagine");
            with(_data){
              myImage.setPosition(5,10);
              myImage.setDimension(55,45);
              myImage.hideMe();
            }
            var lista = [];
            _data.myListBox = new ListBox("listbox", lista, "PAROLE TABOO");
            with(_data){
              myListBox.setPosition(70,10);
              myListBox.setFont(24);
              myListBox.setDimension(40,30);
              myListBox.render("game_area");
              myListBox.hideMe();
            }
            var check = function(){
              if(_data.myInputBox.result() != "") {
                if(_data.myListBox.check(_data.myInputBox.result())){
                  raise( 'next' );
                }else{
                  _data.myListBox.alertElement(_data.myInputBox.result());
                }
              }else{
                alert("empty field");
              }
            }

            _data.myInputBox = new InputBox("inputbox",check,"Invia", false);
            with(_data){
              myInputBox.setClickReset(true);
              myInputBox.setPosition(5,58);
              myInputBox.setDimension(50,50);
              myInputBox.render("game_area");
              myInputBox.clear();
              myInputBox.hideMe();
            }

            _data.myButtonNext = new ButtonWidget("next",function(){raise('start')});
            with(_data){
              myButtonNext.setDimension(10,5);
              myButtonNext.setPosition(30,58);
              myButtonNext.setInnerText("Next");
              myButtonNext.render("game_area");
              myButtonNext.hideMe();
            }

            _data.myButtonYes = new ButtonWidget("Yes",function(){raise('yes')});
            with(_data){
              myButtonYes.setDimension(10,5);
              myButtonYes.setPosition(45,58);
              myButtonYes.setInnerText("Yes");
              myButtonYes.render("game_area");
              myButtonYes.hideMe();
            }

            _data.myButtonNo = new ButtonWidget("No",function(){raise('no')});
            with(_data){
              myButtonNo.setDimension(10,5);
              myButtonNo.setPosition(70,58);
              myButtonNo.setInnerText("No");
              myButtonNo.render("game_area");
              myButtonNo.hideMe();
            }

            _data.myScore = new TextWidget("score");
            with(_data){
              myScore.setDimension(100,30);
              myScore.setPosition(5,10);
              myScore.setFont(20);
              myScore.hideMe();
            }

          </script>

        </onentry>      

        <!--Sub state service.getQuestion -->
        <state id="nuovo_step1">
          <onentry>
            <assign location="_data.obj" expr="new messageQuestion()"></assign>
            <script>
              var dati = ''+_data.gamename;
              var fun = function(){raise('callBack');};
              try{
                _data.service.GetQuestion(dati, _data.obj, fun);
              }catch(e) {
                if(e instanceof IllegalArgumentException)
                  alert('Connection error '+e.toString());
                if(e instanceof ConnectException)
                  alert('Connection error '+e.toString());
              }
            </script>
          </onentry>
          <transition event="callBack" cond="_data.obj.answer == ''" target="nuovo_step2a" />
          <transition event="callBack" cond="(_data.obj.answer != '')" target="nuovo_step2b" />
        </state>

        <!--Sub state render question-->
        <state id="nuovo_step2a">
          <onentry>
            <script>
              _data.rigioca = new ButtonWidget('rigioca',function(){raise('rigioca');});                  
              with(_data){
                if(obj.gameover != undefined &amp;&amp; obj.gameover == 'true' ){
                  rigioca.setPosition(5,5);
                  rigioca.setInnerText('Rigioca');
                  rigioca.render('game_area');                  
                  myScore.setInnerText(''+obj.msg.txt);
                  myScore.render('game_area');
                }
                else {
                  myImage.setUri(obj.idocument[0]);
                  myImage.render("game_area");
                  myImage.showMe('slow');
                  myListBox.setWordList();
                  myListBox.setWordList(obj.subclass.taboo);
                  myListBox.render("game_area");
                  myListBox.showMe('slow');
                  myDescr.setInnerText(obj.text);
                  myDescr.render("game_area");
                  myInputBox.showMe('slow');
                }
              }
            </script>
          </onentry>
          <onexit>
            <script>
              with(_data){
                rigioca.deleteMe();
                delete rigioca;
                myImage.deleteMe();
                myListBox.deleteMe();
                myInputBox.hideMe();
                myDescr.deleteMe();
                myScore.deleteMe();
              }
            </script>
            <assign location="_data.result" expr="_data.myInputBox.result()" />
          </onexit>
          <transition event="rigioca" target="nuovo_step1" >
            <script>
              _data.myStatusWi.sc = 0;
              _data.myStatusWi.setScoreText(0);
            </script>
          </transition>
          <transition event="next" target="nuovo_step3a" />
        </state>

        <!--Sub state service checkAnswer-->
        <state id="nuovo_step3a">
          <onentry>
            <assign location="_data.ans" expr="new messageAnswer()"></assign>
            <script>
              var name = ''+_data.gamename;
              var answer = ''+_data.result;
              var fun = function(){raise('callBack');};
              try{
                _data.service.CheckAnswer(name,answer,_data.ans,fun);
              }catch(e) {
                if(e instanceof IllegalArgumentException)
                  alert('Connection error '+e.toString());
                if(e instanceof ConnectException)
                  alert('Connection error '+e.toString());
              }
            </script>
          </onentry>
          <transition event="callBack" target="nuovo_step4a" />
        </state>

        <!--Sub state render score-->
        <state id="nuovo_step4a">
          <onentry>
            <script>
              with(_data){
                if(ans.score != undefined){
                  myStatusWi.setScoreText(ans.score);
                  myStatusWi.showMe();
                }                
                if(ans.gameover != undefined &amp;&amp; ans.gameover == 'true' ){
                  myScore.setInnerText(''+ans.msg.txt);
                  myScore.render("game_area");
                }else if(ans.score == 1){
                  myScore.setInnerText('Il tuo punteggio è di '+ans.score+' punti');
                }
                else{
                  myScore.setInnerText('Complimenti Il tuo punteggio è di '+ans.score+' punti');
                }
                myScore.render("game_area");
                myButtonNext.showMe();
                
              }
            </script>
          </onentry>
          <onexit>
            <script>
              with(_data){
                myScore.deleteMe();
                myButtonNext.hideMe();
              }
            </script>
          </onexit>
          <transition event="start" target="nuovo_step1" />
        </state>

        <!-- diramazione domande si/no -->
        <state id="nuovo_step2b">
          <onentry>
            <script>
              _data.rigioca = new ButtonWidget('rigioca',function(){raise('rigioca');});
              with(_data){ 
                if(obj.gameover != undefined &amp;&amp; obj.gameover == 'true' ){
                  rigioca.setPosition(5,5);
                  rigioca.setInnerText('Rigioca');
                  rigioca.render('game_area');                  
                  myScore.setInnerText(''+obj.msg.txt);
                  myScore.render("game_area");
                }               
                else {
                  myImage.setUri(obj.idocument[0]);
                  myImage.render("game_area");
                  myImage.showMe('slow');
                  myButtonNo.showMe();
                  myButtonYes.showMe();
                  myDescr.setInnerText(obj.text);
                  myDescr.render("game_area");
                }
              }
            </script>
          </onentry>
          <onexit>
            <script>
              with(_data){
                rigioca.deleteMe();
                delete rigioca;
                myImage.deleteMe();
                myDescr.deleteMe();
                myScore.deleteMe();
                myButtonNo.hideMe();
                myButtonYes.hideMe();
              }
            </script>
          </onexit>
          <transition event="rigioca" target="nuovo_step1" >
            <script>
              _data.myStatusWi.setScoreText(0);
            </script>
          </transition>
          <transition event="yes" target="nuovo_step3b_yes"/>
          <transition event="no" target="nuovo_step3b_no"/>
        </state>

        <state id="nuovo_step3b_yes">
          <onentry>
            <assign location="_data.ans" expr="new messageAnswer()"></assign>
            <script>
              //var dati = new Array();
              //dati['answer'] = 'y-' +_data.obj.answer;
              //dati['gamename'] = ''+_data.gamename;
              var name = ''+_data.gamename;
              var answer = 'y-' +_data.obj.answer;
              var fun = function(){raise('callBack');};
              try{
                _data.service.CheckAnswer(name,answer,_data.ans,fun);
              }catch(e) {
                if(e instanceof IllegalArgumentException)
                  alert('Connection error '+e.toString());
                if(e instanceof ConnectException)
                  alert('Connection error '+e.toString());
              }
            </script>
          </onentry>
          <transition event="callBack" target="nuovo_step4a" />
        </state>

        <state id="nuovo_step3b_no">
          <onentry>
            <assign location="_data.ans" expr="new messageAnswer()"></assign>
            <script>
              var dati = new Array();
              //dati['answer'] = 'n-' +_data.obj.answer;
              //dati['gamename'] = ''+_data.gamename;
              var name = ''+_data.gamename;
              var answer = 'n-' +_data.obj.answer;
              var fun = function(){raise('callBack');};
              try{
                _data.service.CheckAnswer(name,answer,_data.ans,fun);
              }catch(e) {
                if(e instanceof IllegalArgumentException)
                  alert('Invalid argument '+e.toString());
                if(e instanceof ConnectException)
                  alert('Connection error '+e.toString());
              }
            </script>
          </onentry>
          <transition event="callBack" target="nuovo_step4a" />
        </state>
        
        <onexit>
          <script>
            with(_data){
              myStatusWi.deleteMe();
              myDescr.deleteMe();
              myImage.deleteMe();
              myListBox.deleteMe();
              myInputBox.deleteMe();
              myButtonNext.deleteMe();
              myButtonYes.deleteMe();
              myButtonNo.deleteMe();
              myScore.deleteMe();
            }
          </script>
        </onexit>
        
        <!-- transizioni esterne, accedibili da ogni stato--> 
        <transition event="logout" target="UnauthenticatedUserState">
          <script>
            $("#game_area").empty();
            $("#game_area").hide();
            _data.myStatusWi.hideMe();
          </script>
        </transition>
      </state>
      
    </state>
  </parallel>
</scxml>

